﻿using System.Threading.Tasks;

namespace XXX.Workflow
{
	public class WorkItem1 : Sidvall.WorkItemManager.Workflow.WorkItemProviderBase
	{
		#region Public Members

		public WorkItem1Context ContextItem { get; set; }
		public WorkItem1ExecutionContext ExecutionContextItem { get; set; }

		#region ExecuteAsync

		public override async Task<Sidvall.WorkItemManager.Workflow.WorkItemResult> ExecuteAsync()
		{
			byte executionCompletionPercentage;

			// Parse this.ExecutionContext and this.Context
			DeserializeContext();

			for (int i = 0; i < this.ContextItem.ItemCount - 1; i++)
			{
				// Do task
				await Task.Delay(1000).ConfigureAwait(false);

				// Update status so that the progress can be shown to users. When calling this method
				// the IsCanceled flag can be set to indicate that the task should abort.
				SerializeContext();
				executionCompletionPercentage = (byte)(((i + 1) * 100 / this.ContextItem.ItemCount));
				await UpdateExecutionContextAsync(this.ExecutionContext, executionCompletionPercentage).ConfigureAwait(false);

				// Check if the cancel-flag is set. Abort if so is the case.
				if (this.IsCanceled)
					return new Sidvall.WorkItemManager.Workflow.WorkItemResult(Sidvall.WorkItemManager.Workflow.WorkItemResultType.Canceled, "I have been canceled.");
			}

			// Serialize this.ExecutionContext
			SerializeContext();

			return new Sidvall.WorkItemManager.Workflow.WorkItemResult(Sidvall.WorkItemManager.Workflow.WorkItemResultType.Ok, this.ExecutionContext);
		}

		#endregion

		#endregion
		#region Private Members

		#region DeserializeContext

		private void DeserializeContext()
		{
			this.ContextItem = Sidvall.Serialization.SerializerManager.Current.Deserialize<WorkItem1Context>(this.Context);
			this.ExecutionContextItem = Sidvall.Serialization.SerializerManager.Current.Deserialize<WorkItem1ExecutionContext>(this.ExecutionContext);
		}

		#endregion
		#region SerializeContext

		private void SerializeContext()
		{
			this.ExecutionContext = Sidvall.Serialization.SerializerManager.Current.SerializeObject(this.ExecutionContextItem);
		}

		#endregion

		#endregion
	}
}
